
// Copyright (c) 2022 NetEase, Inc. All rights reserved.
// Use of this source code is governed by a MIT license that can be
// found in the LICENSE file.

import UIKit
import NEContactUIKit
import NECoreKit
import NIMSDK
import NECoreIM2Kit
import NEConversationUIKit
import NETeamUIKit
import NEChatUIKit
import NEMapKit
import NERtcCallKit
import NERtcCallUIKit

@main
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, TeamSettingDelegate {
    public var window: UIWindow?
    
    private var tabbarCtrl = UITabBarController()
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        window?.backgroundColor = .white
        setupInit()
        NotificationCenter.default.addObserver(self, selector: #selector(refreshRoot), name: Notification.Name("logout"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(refreshUIStyle), name: Notification.Name(CHANGE_UI), object: nil)
        registerAPNS()
        return true
    }
    
    
    func setupInit(){
        
        // 初始化NIMSDK
        let option = NIMSDKOption()
        option.v2 = true
        option.appKey = AppKey.appKey
        option.apnsCername = AppKey.pushCerName
        
//        let setting = NIMServerSetting()
//        setting.lbsAddress = "https://nim.akimoto-studio.com:443/lbs/conf.jsp"
//        setting.linkAddress = "nim.akimoto-studio.com:10181"
//        setting.nosLbsAddress = "https://nim.akimoto-studio.com:443/ lbs/noslbs.jsp"
//
//        setting.nosUploadAddress = "https://nim.akimoto-studio.com:443"
//        setting.nosUploadHost = "nim.akimoto-studio.com"
//        setting.nosDownloadAddress = "nim.akimoto-studio.com:443/{bucket}/{object}"
//        
//        setting.httpsEnabled = true
//        setting.module = "00b0f6f6f1cd216813b9ba374183b7c4d01ec351649b87f96e6cb2acb234d0910a0191276e1d387eac315c21650cb238b6a5a7ca9c3a12f977fa081bd0ce1640bdb1d23ab16f6ba88325027185dd63aea20904d35e43d8c4e44fdedeadd7c784950fab51a7abd6e80a92bf7c490a83782a788e4df6f6df1be6e3e53b2ae5062f15"
//      
//        setting.cdnEnable = true
//                
//        IMKitClient.instance.serverSetting = setting
//        
        IMKitClient.instance.setupIM(option)
        
        NEAIUserManager.shared.setProvider(provider: self)
        
//        "accid":"xiangyu","token":"71a75ecdc3ed5b70dbba3891ee62bb0b"
        var account = "xiangyu"
        var token = "71a75ecdc3ed5b70dbba3891ee62bb0b"
//        "accid":"zhangrui","token":"c2d119fc3639bfbba6991ca26034cfe5"
//        account = "zhangrui"
//        token = "c2d119fc3639bfbba6991ca26034cfe5"
//        "accid":"akimoto","token":"451b2c1aba615a4881dfef0f0f2cc43b"
//        let account = "akimoto"
//        let token = "451b2c1aba615a4881dfef0f0f2cc43b"
//        "accid":"18678049030","token":"950a6c825993650bca41622b9c36e0f3"
//        account = "18678049030"
//        token = "950a6c825993650bca41622b9c36e0f3"
        
//        let account = "test3"
//        let token = "7d8fa8df470c257d05679934fd876a0e"
        
//         account = "test4"
//         token = "eea61126e75a9442c200fbfc45216734"
        
//        let account = "test5"
//        let token = "c76d7f11c514cc8d6fd16df8bbf27a12"
        
//        let account = "test6"
//        let token = "a2a96fbbb148e9d32abdbf45e5a864ba"
        
//        let account = "1722441405077"
//        let token = "90760756376a102ad4f9539acf6ab592"

//        let account = "1723600800026"
//        let token = "75f763a5d744c657b83c714c3a81d063"
//        
        
//        account = "496696a0"
//        token = "b2aa8f567b31d97352125f232eac1227"
        
        NETeamService.shared.setIfSitEnvironment(true)
        NEChatUIKitClient.instance.delegate = self
        
        loadService()
        
        weak var weakSelf = self
        IMKitClient.instance.login(account, token, nil) { error in
            if let err = error {
                print("login error in app : ", err.localizedDescription)
            }else {
                weakSelf?.initConfig()
                weakSelf?.initializePage()
            }
        }
        
        
        let documentsDirectory = FileManager.SearchPathDirectory.documentDirectory
        let domainMask = FileManager.SearchPathDomainMask.userDomainMask
         
        if let documentsDirectoryPath = NSSearchPathForDirectoriesInDomains(documentsDirectory, domainMask, true).first {
            print(documentsDirectoryPath)
        }
        
    }
    
    @objc func refreshRoot(){
        print("refresh root")
        //loginWithUI()
    }
    
    @objc func refreshUIStyle(){
        initializePage()
    }
    
    func registerAPNS(){
        if #available(iOS 10.0, *) {
            let center = UNUserNotificationCenter.current()
            center.delegate = self
            
            center.requestAuthorization(options: [.badge, .sound, .alert]) { grant, error in
                if grant == false {
                    DispatchQueue.main.async {
                        UIApplication.shared.keyWindow?.makeToast(NSLocalizedString("open_push", comment: ""))
                    }
                }
            }
        } else {
            let setting = UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil)
            UIApplication.shared.registerUserNotificationSettings(setting)
        }
        UIApplication.shared.registerForRemoteNotifications()
        UIApplication.shared.applicationIconBadgeNumber = 0
    }
    
    // TeamSettingDelegate

    //请求群聊支持会议的状态
    var status = false
    func fetchTeamSupportMeetingStatus(teamId: String, complete: @escaping (Bool) -> Void) {
        print(teamId)
        // 请求接口后返回当前状态
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { //模拟请求接口
            complete(self.status)
        }
    }
    
    //更新群聊支持会议状态
    func setTeamSupportMeetingStatus(teamId: String, status: Bool, complete: @escaping (Bool) -> Void) {
        print(teamId)
        // 请求接口后返回当前状态
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { //模拟请求接口
            self.status = status
            //成功返回status
            //complete(status)
            
            //失败返回!status
            complete(self.status)
        }
    }
    
    //点击群聊更多按钮
    func didSelectMoreAction(teamId: String, type: NEMoreActionType) {
        print(teamId)

        if type == .rtc {
            // 发起会议
        }
    }
    
    
    
    
    func applicationWillEnterForeground(_ application: UIApplication) {
        UIApplication.shared.applicationIconBadgeNumber = 0
    }
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        NIMSDK.shared().updateApnsToken(deviceToken)
    }
    
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        NEALog.infoLog("app delegate : ", desc: error.localizedDescription)
    }
    
    // app在前台时不显示推送弹窗
//    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
//        if UIApplication.shared.applicationState == .active {
//            // 应用处于前台，不显示弹窗
//            completionHandler([])
//        } else {
//            // 应用处于后台或非活动状态，正常显示弹窗
//            completionHandler(.alert)
//        }
//    }
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {
        if  UIApplication.shared.applicationState == .active {
            // 应用处于前台，不显示弹窗
            print("应用处于前台，不显示弹窗")
            return []
        } else {
            // 应用处于后台或非活动状态，正常显示弹窗
            print("显示弹窗")
            return [.alert]
        }
    }
    
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
        if application.applicationState == .active {
            // 应用处于前台，不显示弹窗
            print("应用处于前台，不显示弹窗")
        } else {
            // 应用处于后台或非活动状态，正常显示弹窗
            print("显示弹窗")
        }
    }
    
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        
        let teamId = "27748927142"
        
        let nav = (application.windows.first?.rootViewController as? NETabBarController)?.selectedViewController as? UINavigationController

        if let conversationId = V2NIMConversationIdUtil.teamConversationId(teamId) {
            
//            let teamVC = TeamChatViewController(conversationId: conversationId, anchor: nil)
//            
//            for (i, vc) in (nav?.viewControllers ?? []).enumerated() {
//              if vc.isKind(of: ChatViewController.self) {
//                nav?.viewControllers[i] = teamVC
//                nav?.popToViewController(teamVC, animated: true)
//                return
//              }
//            }
//            
//            nav?.tabBarController?.hidesBottomBarWhenPushed = true
//            nav?.pushViewController(teamVC, animated: true)
            
            
          var params = [String: Any]()
          params["nav"] = nav as Any
          params["conversationId"] = conversationId as Any
          Router.shared.use(PushTeamChatVCRouter, parameters: params, closure: nil)
        }
        
//        Router.shared.use(PushTeamChatVCRouter, parameters: ["nav": (application.windows.first?.rootViewController as? NETabBarController)?.selectedViewController as Any, "conversationId" :"27748927142"]);

        
        completionHandler(.newData)
    }
    
    func initializePage() {
        self.window?.rootViewController = NETabBarController(true)
    }
    
    func initConfig() {
        //地图组件初始化
        NEMapClient.shared().setupMapClient(withAppkey: AppKey.gaodeMapAppkey, withServerKey: AppKey.gaodeMapServerAppkey)
        
        //呼叫组件初始化
        let setupConfig = NESetupConfig(appkey: AppKey.appKey)
        NECallEngine.sharedInstance().setup(setupConfig)
        NECallEngine.sharedInstance().setTimeout(30)
        
        let uiConfig = NECallUIKitConfig()
        NERtcCallUIKit.sharedInstance().setup(with: uiConfig)
    }
    
    //    regist router
    func loadService() {
        
        ChatKitClient.shared.setupInit(isFun: !NEStyleManager.instance.isNormalStyle())
        
        // 自定义示例
        customVerification()
        
        Router.shared.register(MeSettingRouter) { param in
            if let nav = param["nav"] as? UINavigationController {
                let me = PersonInfoViewController()
                nav.pushViewController(me, animated: true)
            }
        }
    }
    
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        return .portrait
    }
    
    func customVerification(){
        Router.shared.register(TeamSettingViewRouter) { param in
            print("param:\(param)")
            let nav = param["nav"] as? UINavigationController
            guard let teamid = param["teamid"] as? String else {
                return
            }
            
            let teamSettingVC = TeamSettingViewController()
            teamSettingVC.teamId = teamid
            nav?.pushViewController(teamSettingVC, animated: true)
        }
        
        
        if NEStyleManager.instance.isNormalStyle() {
            Router.shared.register(PushP2pChatVCRouter) { param in
                print("param:\(param)")
                let nav = param["nav"] as? UINavigationController
                guard let conversationId = param["conversationId"] as? String else {
                    return
                }
                let anchor = param["anchor"] as? V2NIMMessage
                let p2pChatVC = CustomNormalChatViewController(conversationId: conversationId, anchor: anchor)
                
                for (i, vc) in (nav?.viewControllers ?? []).enumerated() {
                    if vc.isKind(of: ChatViewController.self) {
                        nav?.viewControllers[i] = p2pChatVC
                        nav?.popToViewController(p2pChatVC, animated: true)
                        return
                    }
                }
                if let remove = param["removeUserVC"] as? Bool, remove {
                    nav?.viewControllers.removeLast()
                }
                
                nav?.pushViewController(p2pChatVC, animated: true)
            }
        } else {
            Router.shared.register(PushP2pChatVCRouter) { param in
                print("param:\(param)")
                let nav = param["nav"] as? UINavigationController
                guard let conversationId = param["conversationId"] as? String else {
                    return
                }
                let anchor = param["anchor"] as? V2NIMMessage
                let p2pChatVC = CustomFunChatViewController(conversationId: conversationId, anchor: anchor)
                
                for (i, vc) in (nav?.viewControllers ?? []).enumerated() {
                    if vc.isKind(of: ChatViewController.self) {
                        nav?.viewControllers[i] = p2pChatVC
                        nav?.popToViewController(p2pChatVC, animated: true)
                        return
                    }
                }
                
                if let remove = param["removeUserVC"] as? Bool, remove {
                    nav?.viewControllers.removeLast()
                }
                
                nav?.pushViewController(p2pChatVC, animated: true)
            }
        }
    }
}

extension AppDelegate: AIUserAgentProvider {
    public func getAISearchUser(_ users: [V2NIMAIUser]) -> V2NIMAIUser? {
        for user in users {
            if user.accountId == "search" {
                return user
            }
        }
        return nil
    }
    
    public func getAITranslateUser(_ users: [V2NIMAIUser]) -> V2NIMAIUser? {
        for user in users {
            if user.accountId == "translation" {
                return user
            }
        }
        return nil
    }
    
    public func getAITranslateLangs(_ users: [V2NIMAIUser]) -> [String] {
        ["英语", "日语", "韩语", "俄语", "法语", "德语"]
    }
}
